const http = require('http');
const url = require('url');
const querystring = require('querystring');

const server = http.createServer((req, res) => {
  const url_obj = url.parse(req.url)
  const params = querystring.parse(url_obj.query)
  const req_url = url_obj.pathname

  switch (req_url) {
    case '/user/findById':
      const user = { id: params.id, name: 'terry', age: 12, gender: 'female' }
      // 响应头信息
      res.writeHead(200, 'OK', {
        "Content-Type": 'appliction/json'
      })
      // 响应结果
      res.write(JSON.stringify({
        status: 200,
        message: '查询成功',
        data: user,
        timestamp: new Date().getTime()
      }))
      break;
    case '/user/save':
      const method = req.method

      let data = []
      if (method == 'POST') {
        req.on('data', chunk => {
          data += chunk
        })
        req.on('end', () => {
          console.log(querystring.parse(data.toString()));
        })
        // 响应头信息
        res.writeHead(200, 'OK', {
          "Content-Type": "application/json"
        })
        res.write(JSON.stringify({
          status: 200,
          message: '保存成功',
          data: null,
          timestamp: new Date().getTime()
        }))


      } else {
        res.writeHead(400, 'Not Method', {
          "Content-Type": "text/html?charset=utf-8"
        })
        res.write('<p>请求方法错误</p>')
      }

      break;
  }


  res.end();
})

server.listen(3000, '127.0.0.1', () => {
  console.log('localhost:3000服务器已开启......');
})